#include "serialport.h"
#include <QSerialPortInfo>
#include <QDebug>

SerialPort::SerialPort(QObject *parent) : QSerialPort(parent)
{
    const auto infos = QSerialPortInfo::availablePorts();
    for (const QSerialPortInfo &info : infos) // 获取CMO口
    {
        QSerialPort serial;
        serial.setPort(info);
        if (serial.open(QIODevice::ReadWrite))
        {
            //            ui->port_number_Box->addItem(info.portName()); //加载串口号
            Port_name.append(info.portName());
            serial.close();
        }
    }

    connect(this, &QSerialPort::readyRead, this, &SerialPort::Read_cb);
    connect(this, &QSerialPort::bytesWritten, this, &SerialPort::Write_cb);

    Read_timeout.setSingleShot(true);
    Write_timeout.setSingleShot(true);
    connect(&Read_timeout, &QTimer::timeout, this, &SerialPort::Read_timer_timeout);   // 串口读取计时器
    connect(&Write_timeout, &QTimer::timeout, this, &SerialPort::Write_timer_timeout); // 串口接收计时器
}
/*
 * 设置超时时间
 */
void SerialPort::Set_timeout(int ms)
{
    Timeout_times = ms;
}
int SerialPort::Open(QString PortName)
{

    this->setPortName(PortName); // 设置端口名字为当前设置的值
    if (this->open(QIODevice::ReadWrite))
    {
        this->PortName = PortName;
        this->flush();
        this->clear();
        return 1;
    }
    return 0;
}

void SerialPort::Close(void)
{
    this->flush();
    this->clear();
    this->close();
}

void SerialPort::Write(QByteArray data, qint16 len)
{
    if (isOpen())
    {
        this->write(data, len);
    }
}
/*
 * 数据读取槽函数
 */
void SerialPort::Read_cb(void)
{
    QByteArray buf;
    buf = this->readAll(); // 读取所有串口数据

    Read_buffer += buf;

    //    Read_timeout.stop();
    Read_timeout.start(Timeout_times);

    qDebug() << "Read_cb";
}

void SerialPort::Write_cb(qint64 bytes)
{
    Q_UNUSED(bytes);
    Write_timeout.start(60);
}

/*
 * 数据读取完成
 */
void SerialPort::Read_timer_timeout(void)
{
    Read_timeout.stop();

    if (!Read_buffer.isEmpty())
    { // 如果不是空
        emit ReadComplete(Read_buffer, Read_buffer.length());
        Read_buffer.clear();
    }

    qDebug() << "Read_timer_timeout";
}
void SerialPort::Write_timer_timeout(void)
{
    emit WriteComplete();
}
